<template>
  <div>
    <div class="handle-box">
      <el-row>
        <el-button v-if="threeLevelsbool.addName" type="primary" class="handle-del" @click="addDataFrom" style="float: left; margin-right: 10px">新增客户
        </el-button>
        <!-- http://www.dazhimu.cc/customers/uploadExcel -->
        <el-upload v-if="threeLevelsbool.ruExcel" class="upload-demo" ref="upload" action="https://www.dazhimu.cc/customers/uploadExcel"
                   :headers="uploadHeader" :limit="1" accept=".xlsx" :data="uploadData" :on-success="fileChange" :on-progress="fileloadChange"
                   :show-file-list="false" style="float: left; margin-right: 10px">
          <el-button size="small" type="primary" :loading="excelLoad">导入excel</el-button>
        </el-upload>
        <template>
          <el-button v-if="threeLevelsbool.chuExcel" type="primary" class="handle-del" :loading="exceltrueFlg" @click="exceltrue"
                     style="float: left; margin-right: 10px">导出excel</el-button>
          <el-button v-else type="primary" class="handle-del" :loading="excelfalseFlg" @click="excelfalse" style="float: left; margin-right: 10px">
            导出excel</el-button>
        </template>
        <el-button size="small" type="primary"><a href="https://daidaiwang-1307355890.cos.ap-beijing.myqcloud.com/customersInfo.xlsx"
             style="color:#fff;" target="_black">下载excel模板</a></el-button>
        <el-button v-if="threeLevelsbool.guowang" size="small" type="primary" @click="pastClick">过往导入重复数据</el-button>
      </el-row>
      <div style="margin-top: 15px">
        <el-button v-if="threeLevelsbool.huiHai" type="primary" class="handle-del" @click="handleEdit">捞取/分配</el-button>
        <el-button v-if="threeLevelsbool.pigonghai" type="warning" class="handle-del" @click="newDongfn">重新分配公海</el-button>
        <el-button v-if="threeLevelsbool.pikehu" type="danger" class="handle-del mr10" @click="seasListDel">批量删除</el-button>
        <el-select v-model="query.isRepeat" placeholder="选择数据类型" class="mr10">
          <el-option label="全部数据" value=""></el-option>
          <el-option label="无重复标识数据" value="0"></el-option>
          <el-option label="有重复标识数据" value="1"></el-option>
        </el-select>
        <el-select v-model="query.city" filterable placeholder="选择归属地" class="mr10">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="item in ascriptionArr" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="handle-box" style="margin-top: 15px">
        <el-date-picker class="mr10" v-model="startTime_endTime" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
        <el-input v-model="query.kw" placeholder="请输入用户名/电话查询" class="handle-input mr10" style="width:400px;"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="tableData" border class="table" style="width: 100%" ref="multipleTable" header-cell-class-name="table-header"
              @selection-change="handleSelectionChange" @filter-change="levelChange" @sort-change="sortChange">
      <el-table-column type="selection" fixed="left" width="55" align="center"></el-table-column>
      <el-table-column type="index" fixed="left" :index="tableIndex" label="序号" width="100" align="center"></el-table-column>
      <el-table-column prop="cName" fixed="left" label="客户名称" width="120">
        <template slot-scope="scope">
          <el-link v-if="threeLevelsbool.editName" type="primary" :underline="false" @click="drawerStateClick(scope.row.cId, scope.row.cIsFlag)">
            <el-tag v-if="scope.row.extParam2 == 1" size="mini" type="warning" :style="{'marginRight':'5px'}">重复</el-tag>{{ scope.row.cName }}
          </el-link>
          <el-link v-else type="primary" :underline="false">
            <el-tag v-if="scope.row.extParam2 == 1" size="mini" type="warning" :style="{'marginRight':'5px'}">重复</el-tag>{{ scope.row.cName }}
          </el-link>
          <span v-if="threeLevelsbool.editName && win.tccc" class="tccctel" @click="tcccClick(scope.row.cId, scope.row.cIsFlag)"><i
               class="el-icon-phone-outline"></i>云</span>

        </template>
      </el-table-column>
      <el-table-column prop="cPhone" label="电话" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.cPhone }}</span>
          <i v-if="threeLevelsbool.editName" class="el-icon-phone" :style="{'fontSize':'20px','color':'#409EFF','cursor':'pointer'}"
             @click="clickTel(scope.row.cId, scope.row.cIsFlag)"></i>
        </template>
      </el-table-column>
      <el-table-column label="客户级别" width="120" column-key="jibie"
                       :filters="[{text:'A(重要客户)',value:'A'},{text:'B(优质客户)',value:'B'},{text:'C(普通客户)',value:'C'}]" filter-placement="bottom-end"
                       :filter-method="filterTag">
        <template slot-scope="scope">{{
                    scope.row.cLevel === 'A' ? 'A(重要客户)' : scope.row.cLevel === 'B' ? 'B(优质客户)' : 'C(普通客户)'
                }}</template>
      </el-table-column>
      <el-table-column prop="newFollowUpRecord" label="最新跟进记录" width="180"></el-table-column>
      <el-table-column prop="newFollowUpTime" sortable="custom" label="最新跟进时间" width="200"></el-table-column>
      <el-table-column prop="fromName" label="客户来源" width="120"></el-table-column>
      <el-table-column prop="cCreateTime" sortable="custom" label="创建时间" width="200"></el-table-column>
      <el-table-column label="成交状态" align="center" fixed="right" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.cStatus === '0'" type="primary">待跟进</el-tag>
          <el-tag v-if="scope.row.cStatus === '1'" type="success">已签约</el-tag>
          <el-tag v-if="scope.row.cStatus === '2'" type="primary">已跟进/在考虑</el-tag>
          <el-tag v-if="scope.row.cStatus === '3'" type="primary">已邀约/待上门</el-tag>
          <el-tag v-if="scope.row.cStatus === '4'" type="primary">已沟通/不需要</el-tag>
          <el-tag v-if="scope.row.cStatus === '5'" type="primary">已上门/待签约</el-tag>
          <el-tag v-if="scope.row.cStatus === '6'" type="primary">已上门/资质不符</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button v-if="threeLevelsbool.removeName" type="text" icon="el-icon-delete" class="red" @click="delList(scope.row.cId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background layout="total,sizes, prev, pager, next,jumper" :current-page="query.page" :page-size="query.limit"
                     :page-sizes="[10, 20, 30, 40, 50, 60, 70, 80, 90, 100,200,500]" :total="totalCount" :pager-count="5"
                     @size-change="handlePageSelectChange" @current-change="handlePageChange" @prev-click="handlePageChange"
                     @next-click="handlePageChange"></el-pagination>
    </div>

    <!-- 分配数据弹出框 -->
    <el-dialog title="分配数据" :visible.sync="editVisible" width="30%" :close-on-click-modal="false">
      <el-row v-loading="loadingfenFormLoad">
        <!-- <el-input v-model="keyWord" placeholder="请输入姓名查询" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleEdit">搜索</el-button>
        <el-row style="margin-top: 20px"> -->

        <div v-for="e in comData">
          <p style="margin-bottom:15px;font-weight: bold;">{{e.name}} ({{e.str}})</p>
          <div>
            <el-radio-group v-model="fenFormType" style="width: 100%">
              <el-col :span="6" v-for="(item, i) in e.arr" style="margin-bottom: 20px">
                <el-radio :label="item.id">{{ item.name }}</el-radio>
              </el-col>
            </el-radio-group>
          </div>
        </div>

        <!-- <el-radio-group v-model="fenFormType" style="width: 100%">
            <el-col :span="6" v-for="(item, i) in fenFormDataArr" style="margin-bottom: 20px">
              <el-radio :label="item.id">{{ item.name }}</el-radio>
            </el-col>
          </el-radio-group> -->
      </el-row>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit" :loading="loadingfenFormLoad">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 过往导入重复数据 -->
    <el-dialog title="过往导入重复数据记录" :visible.sync="PastFlg" width="50%" :close-on-click-modal="false">
      <el-row :style="{'marginBottom':'10px'}">
        <el-select v-model="PastSelval" placeholder="请选择要查询的上传批次" class="mr10" :style="{'width':'500px'}">
          <el-option v-for="item in PastSelArr" :label="'日期：'+item.importTime+' 批次号：'+item.batchNo" :value="item.batchNo"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="pastTemSou">搜索</el-button>
      </el-row>
      <el-row>
        <el-table :data="PastTabel" style="width: 100%">
          <el-table-column prop="batchNo" label="批次" width="180"></el-table-column>
          <el-table-column prop="importNum" label="总数"></el-table-column>
          <el-table-column prop="repeatNum" label="重复数"></el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="primary" @click="pastGet(scope.row.batchNo)" :loading="PastTabelBtnLoad">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="PastFlg = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 重新分配公海 -->
    <el-dialog title="重新分配公海" :visible.sync="newGongFlg" width="30%" :close-on-click-modal="false">
      <el-radio-group v-model="newGongId" style="width: 100%">
        <el-col :span="12" v-for="item in listArr" style="margin-bottom: 20px">
          <el-radio :label="item.hsId">{{ item.hsName }}</el-radio>
        </el-col>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="newGongFlg = false">取消</el-button>
        <el-button type="primary" @click="newGongSub" :loading="newGongLoad">确定</el-button>
      </span>
    </el-dialog>
    <!-- 查看客户信息窗口 -->
    <customer-model ref="drawerState" :activeIndexId="activeIndexId" @fathergetData="getData" :key="keyFlag"></customer-model>
  </div>
</template>
<script>
import {
  InternationalWatersTableAjax,
  InternationalWatersTeamUserAjax,
  InternationalWatersDistributionAjaxSub,
  RolePermissionsQX,
  ExcelZha,
  ExcelChu,
  customerFormRemove,
  GHpast,
  GHdow,
  GHnewGongSub,
  getAscription,
  PersonnelBUInfo,
  PersonnelLists,
  customerTel
} from '../../../../api/index';
import customermodel from '../../../common/customermodel';
import Storage from '../../../../utils/localStorage';
import cityData from '../../../../utils/city'
export default {
  data() {
    return {
      win: window,
      cityData: cityData,
      editVisible: false,
      loading: true,
      startTime_endTime: [],
      query: {
        page: 1,
        limit: 10,
        startTime: '',
        endTime: '',
        kw: '',
        isRepeat: '',
        city: '',
        //筛选
        leavels: [],
        orderbyfollowup: 0,
        orderbycreate: 0,
        orderdo: '',

      },
      totalCount: 0,
      totalPage: 0,
      ascriptionArr: [],

      tableData: [],
      multipleSelection: [],

      loadingfenFormLoad: true,
      fenFormDataArr: [],
      fenFormType: '',
      keyWord: '',

      keyFlag: '',

      excelfalseFlg: false,
      exceltrueFlg: false,

      uploadData: {
        seasId: ''
      },
      excelLoad: false,
      uploadHeader: { Authorization: Storage.getItem('token') ? Storage.getItem('token') : '1' },

      //过往数据查询
      PastFlg: false,
      PastSelval: '',
      PastSelArr: [],
      PastTabel: [],
      PastTabelBtnLoad: false,
      //延时器
      timeoutName: '',
      //公司部门结构
      comData: [],
      //重新分配公海
      newGongFlg: false,
      newGongLoad: false,
      newGongId: '',
    };
  },
  props: ['activeIndexId', 'threeLevelsbool', 'listArr'],
  components: {
    'customer-model': customermodel
  },
  created() {
    if (this.activeIndexId) {
      this.getData();
      this.uploadData.seasId = this.activeIndexId;
    } else {
      this.tableData = [];
      this.loading = false;
    }
    this.getcom();
  },
  methods: {
    // 获取 easy-mock 的模拟数据
    getData() {
      this.loading = true;
      this.query.seasId = this.activeIndexId;
      if (typeof (this.query.leavels) == 'object') {
        this.query.leavels = this.query.leavels.length > 0 ? this.query.leavels.join(',') : '';
      }
      InternationalWatersTableAjax(this.query).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          this.tableData = res.recordList;
          this.totalCount = res.totalCount;
          this.totalPage = res.totalPage;
        } else {
          this.$message(res.msg);
        }
      });
      getAscription().then((res) => {
        if (res.code == 0) {
          this.ascriptionArr = res.cityList;
        } else {
          this.$message(res.msg);
        }
      });

    },
    //获取部门结构
    getcom() {
      PersonnelBUInfo().then(res => {
        if (res.code == 0) {
          res.teamList.forEach((item, i) => {
            item.childTeam.forEach((e, index) => {
              this.comData.push({
                name: e.name,
                city: e.tCityCode,
                str: '',
                id: e.id,
                arr: [],
              })
            })
          })
          this.comData.forEach(e => {
            if (e.city) {
              this.cityData.forEach(item => {
                if (e.city.slice(0, 2) == item.code.slice(0, 2)) {
                  e.str = item.label;
                  item.children.forEach(ev => {
                    if (ev.code == e.city) {
                      e.str += ev.label;
                    }
                  })
                }
              })
            }
          })
        } else {
          this.$message(res.msg);
        }
      })
    },
    //序号
    tableIndex(index) {
      return (this.query.page - 1) * this.query.limit + index + 1;
    },
    // 分页切换
    handlePageChange(val) {
      this.loading = true;
      this.$set(this.query, 'page', val);
      clearTimeout(this.timeoutName);
      this.timeoutName = setTimeout(() => {
        this.getData();
      }, 300);
    },
    // 分页调整
    handlePageSelectChange(val) {
      this.loading = true;
      this.$set(this.query, 'limit', val);
      this.getData();
    },
    //列表客户等级筛选
    filterTag(value, row, column) {
      return true;
    },
    //筛选时间监听
    levelChange(filters) {
      console.log(filters);
      this.query.leavels = filters.jibie ? filters.jibie : [];
      this.getData();
    },
    //列表时间日期排序
    sortChange(item) {
      console.log(item);
      if (item.prop == 'newFollowUpTime') {
        this.query.orderdo = 2;
        this.query.orderbyfollowup = item.order == 'ascending' ? 1 : item.order == 'descending' ? 2 : 0;
      }
      if (item.prop == 'cCreateTime') {
        this.query.orderdo = 1;
        this.query.orderbycreate = item.order == 'ascending' ? 1 : item.order == 'descending' ? 2 : 0;
      }
      this.getData();
    },
    //搜索
    handleSearch() {
      this.query.page = 1;
      if (this.startTime_endTime) {
        this.query.startTime = this.startTime_endTime[0];
        this.query.endTime = this.startTime_endTime[1];
      } else {
        this.query.startTime = '';
        this.query.endTime = '';
      }
      this.getData();
    },
    //点击查看客户信息
    drawerStateClick(id, flag, tccc) {
      this.keyFlag = 'edit';
      setTimeout(() => {
        this.$refs.drawerState.drawerStateClick(id, flag, tccc);
      }, 100);
    },
    // 多选操作
    handleSelectionChange(val) {
      let arr = [];
      val.forEach((item, i) => {
        arr.push(item.cId);
      });
      this.multipleSelection = arr;
    },
    // 分配数据
    handleEdit() {
      if (this.multipleSelection.length > 0) {
        this.editVisible = true;
        this.comData.forEach((item, i) => {
          PersonnelLists({
            page: 1,
            limit: 100000000,
            teamId: item.id
          }).then(res => {
            item.arr = res.userList;
          })
        })
        this.loadingfenFormLoad = false;
        // InternationalWatersTeamUserAjax({ keyWord: this.keyWord }).then((res) => {
        //   this.loadingfenFormLoad = false;
        //   if (res.code == 0) {
        //     this.fenFormDataArr = res.userList;
        //   } else {
        //     this.$message(res.msg);
        //   }
        // });
      } else {
        this.$message('请选择需要分配的信息');
      }
    },
    // 确认分配的人
    saveEdit() {
      this.loadingfenFormLoad = true;
      InternationalWatersDistributionAjaxSub({
        cusIds: this.multipleSelection,
        userId: this.fenFormType,
        seasId: this.activeIndexId
      }).then((res) => {
        this.editVisible = false;
        if (res.code === 0) {
          this.$message.success('分配成功');
          this.multipleSelection = [];
          this.getData();
        } else {
          this.$message(res.msg);
        }
      });
    },
    //新增
    addDataFrom() {
      this.keyFlag = 'add';
      setTimeout(() => {
        this.$refs.drawerState.drawerStateAdd();
      }, 100);
    },
    //删除客户
    delList(id) {
      this.$confirm('确定删除当前客户吗？', '删除客户', {
        type: 'warning'
      })
        .then(() => {
          this.loading = true;
          customerFormRemove({ cusId: id }).then((res) => {
            if (res.code === 0) {
              this.$message.success("删除成功");
              this.getData();
            } else {
              this.$message(res.msg);
            }
          });
        })
        .catch(() => { });
    },
    //点击导出（假）
    excelfalse() {
      if (this.multipleSelection.length > 0) {
        this.excelfalseFlg = true;
        ExcelZha({ cusIds: this.multipleSelection }).then((res) => {
          this.excelfalseFlg = false;
          if (res.code === 0) {
            this.$message('导出失败，请联系管理员');
          } else {
            // this.$message(res.msg);
          }
        });
      } else {
        this.$message('请选择要导出的数据');
      }
    },
    //点击导出（真）
    exceltrue() {
      this.$confirm("导出过程中请不要刷新或者离开页面", "提示", {
        type: 'warning',
      }).then(() => {
        if (this.multipleSelection.length > 0) {
          this.exceltrueFlg = true;
          ExcelChu({ cusIds: this.multipleSelection }).then((res) => {
            this.exceltrueFlg = false;
            const link = document.createElement('a');
            let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
            link.download = "客户信息";
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            this.$message.success('导出成功');
          });
        } else {
          this.$message('请选择要导出的数据');
        }
      })
    },
    //导入中
    fileloadChange(event, file, fileList) {
      this.excelLoad = true;
    },
    //导入成功
    fileChange(response, file, fileList) {
      this.excelLoad = false;
      this.$refs.upload.clearFiles();
      if (response.code === 0) {
        this.PastSelval = response.batchNo;
        this.$message.success('上传成功');
        this.getData();
        this.pastClick('flg');
      } else {
        this.$message('上传失败');
      }
    },
    //过往数据点击
    pastClick(flg) {
      this.PastFlg = true;
      GHpast().then(res => {
        if (res.code == 0) {
          this.PastSelArr = res.records;
          if (flg) {
            this.pastTemSou();
          }
        } else {
          this.$message(res.msg);
        }
      })
    },
    //过往数据批次过滤
    pastTemSou() {
      this.PastTabel = [];
      this.PastSelArr.forEach(item => {
        if (this.PastSelval == item.batchNo) {
          this.PastTabel.push(item);
        }
      })
    },
    //过往数据批次下载
    pastGet(id) {
      this.PastTabelBtnLoad = true;
      GHdow({ batchNo: id }).then(res => {
        this.PastTabelBtnLoad = false;
        const link = document.createElement('a');
        let blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' });
        link.download = id + "批次重复数据列表";
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.$message.success('导出成功');
      })
    },
    //重新分配公海
    newDongfn() {
      if (this.multipleSelection.length > 0) {
        this.newGongFlg = true;
      } else {
        this.$message('请选择线索');
      }
    },
    //重新分配公海提交
    newGongSub() {
      this.newGongLoad = true;
      GHnewGongSub({
        cusIds: this.multipleSelection,
        seasId: this.newGongId
      }).then(res => {
        this.newGongLoad = false;
        this.newGongFlg = false;
        if (res.code == 0) {
          this.$message.success('操作成功');
          this.getData();
        } else {
          this.$message(res.msg);
        }
      })
    },
    //批量删除数据
    seasListDel() {
      if (this.multipleSelection.length > 0) {
        this.$confirm('确定删除当前选择线索吗？', '删除线索', {
          type: 'warning'
        }).then(() => {
          this.loading = true;
          this.multipleSelection.forEach((item, i) => {
            customerFormRemove({ cusId: item }).then((res) => {
              if (res.code === 0) {
                //成功
              }
              if (i == this.multipleSelection.length - 1) {
                this.getData();
                this.$message.success("删除完成");
              }
            });
          })
        }).catch(() => { });
      } else {
        this.$message('请选择线索');
      }
    },
    //点击拨号
    clickTel(id, flg) {
      this.drawerStateClick(id, flg);
      customerTel({ cusId: id }).then(res => {
        if (res.code == 0) {
          this.$message.success("开始拨号");
        } else {
          this.$message(res.msg);
        }
      })
    },
    //点击云呼叫
    tcccClick(id, flg) {
      if (!window.tccc) {
        this.$message("暂未开通云呼功能，请联系管理员");
        return;
      }
      this.drawerStateClick(id, flg, 'tccc');
    },
  }
};
</script>
<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.IconColor {
    color: #e6a23c;
}
/deep/ :focus {
    outline: 0;
}
.el-drawer__title {
    color: #72767b;
    -webkit-box-align: center;
    align-items: center;
    margin-bottom: 25px;
    padding: 20px 35px 0;
}
.el-drawer__title span {
    font-size: 14px;
    color: #66b1ff;
    margin: 20px;
    cursor: pointer;
}
.el-radio {
    margin-right: 0px;
}
.beizhu_text {
    height: 794px;
    overflow: auto;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    margin-left: 35px;
    padding: 20px;
    box-sizing: border-box;
    color: #72767b;
    font-size: 14px;
}
.beizhu_text > div:first-child {
    padding-top: 0;
}
.beizhu_text > div {
    padding: 5px 0;
}
.el-icon-star-on {
    font-size: 20px;
}
</style>